package com.lsf.modules.base.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.lsf.common.api.dto.LogDTO;
import com.lsf.modules.base.mapper.BaseCommonMapper;
import com.lsf.modules.base.service.BaseCommonService;
import com.lsf.modules.base.vo.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;

/**
 * common实现类
 *
 * @author Alexander
 */
@Service
@Slf4j
public class BaseCommonServiceImpl implements BaseCommonService {

    @Resource
    private BaseCommonMapper baseCommonMapper;

    @Override
    public void addLog(LogDTO logDTO) {
        if (StringUtils.isEmpty(logDTO.getId())) {
            logDTO.setId(String.valueOf(IdWorker.getId()));
        }
        //保存日志(异常捕获处理,防止数据太大存储失败,导致业务失败)
        try {
            baseCommonMapper.saveLog(logDTO);
        } catch (Exception e) {
            log.warn(" LogContent length : " + logDTO.getLogContent().length());
            log.warn(e.getMessage());
        }
    }

    @Override
    public void addLog(String logContent, Integer logType, Integer operateType, LoginUser user) {
        LogDTO logDTO = new LogDTO();
        logDTO.setId(String.valueOf(IdWorker.getId()));
        //注解上的描述,日志操作内容
        logDTO.setLogContent(logContent);
        logDTO.setLogType(logType);
        logDTO.setOperateType(operateType);
        //获取登录用户信息
        if (user == null) {
            try {
                user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            } catch (Exception e) {
                log.warn(e.getMessage());
            }
        }
        if (user != null) {
            logDTO.setUsername(user.getUsername());
        }
        logDTO.setCreateTime(new Date());
        //保存日志（异常捕获处理,防止数据太大存储失败,导致业务失败）
        try {
            baseCommonMapper.saveLog(logDTO);
        } catch (Exception e) {
            log.warn(" LogContent length : " + logDTO.getLogContent().length());
            log.warn(e.getMessage());
        }
    }

    @Override
    public void addLog(String logContent, Integer logType, Integer operateType) {
        addLog(logContent, logType, operateType, null);
    }
}
